import React, { useState } from 'react';
import { Users, Plus, Edit2, Trash2, Shield, ShieldOff, RotateCcw, Search } from 'lucide-react';

interface Guard {
  id: string;
  name: string;
  employeeId: string;
  district: string;
  status: 'active' | 'inactive';
  lastLogin?: string;
  permissions: string[];
  createdAt: string;
}

export const GuardManagement: React.FC = () => {
  const [guards, setGuards] = useState<Guard[]>([
    {
      id: 'G001',
      name: '张门卫',
      employeeId: 'EMP001',
      district: '东区',
      status: 'active',
      lastLogin: '2024-12-01 15:30:00',
      permissions: ['访客核验', '记录查询'],
      createdAt: '2024-11-01 09:00:00'
    },
    {
      id: 'G002',
      name: '王门卫',
      employeeId: 'EMP002',
      district: '西区',
      status: 'active',
      lastLogin: '2024-12-01 13:15:00',
      permissions: ['访客核验', '记录查询'],
      createdAt: '2024-11-05 14:30:00'
    },
    {
      id: 'G003',
      name: '李门卫',
      employeeId: 'EMP003',
      district: '南区',
      status: 'inactive',
      permissions: ['访客核验'],
      createdAt: '2024-10-15 11:20:00'
    }
  ]);

  const [searchTerm, setSearchTerm] = useState('');
  const [filterDistrict, setFilterDistrict] = useState('all');
  const [filterStatus, setFilterStatus] = useState('all');
  const [showAddModal, setShowAddModal] = useState(false);
  const [editingGuard, setEditingGuard] = useState<Guard | null>(null);

  const [formData, setFormData] = useState({
    name: '',
    employeeId: '',
    district: '东区',
    permissions: [] as string[]
  });

  const districts = ['东区', '西区', '南区', '北区'];
  const availablePermissions = ['访客核验', '记录查询', '统计查看'];

  const filteredGuards = guards.filter(guard => {
    const matchesSearch = guard.name.includes(searchTerm) || 
                         guard.employeeId.includes(searchTerm);
    const matchesDistrict = filterDistrict === 'all' || guard.district === filterDistrict;
    const matchesStatus = filterStatus === 'all' || guard.status === filterStatus;
    return matchesSearch && matchesDistrict && matchesStatus;
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (editingGuard) {
      // Update existing guard
      setGuards(guards.map(guard =>
        guard.id === editingGuard.id
          ? { ...guard, ...formData }
          : guard
      ));
      setEditingGuard(null);
    } else {
      // Add new guard
      const newGuard: Guard = {
        id: `G${(guards.length + 1).toString().padStart(3, '0')}`,
        ...formData,
        status: 'active',
        createdAt: new Date().toLocaleString()
      };
      setGuards([newGuard, ...guards]);
    }
    
    resetForm();
  };

  const resetForm = () => {
    setFormData({
      name: '',
      employeeId: '',
      district: '东区',
      permissions: []
    });
    setEditingGuard(null);
    setShowAddModal(false);
  };

  const handleEdit = (guard: Guard) => {
    setEditingGuard(guard);
    setFormData({
      name: guard.name,
      employeeId: guard.employeeId,
      district: guard.district,
      permissions: guard.permissions
    });
    setShowAddModal(true);
  };

  const handleToggleStatus = (id: string) => {
    setGuards(guards.map(guard =>
      guard.id === id
        ? { ...guard, status: guard.status === 'active' ? 'inactive' : 'active' }
        : guard
    ));
  };

  const handleResetPassword = (guard: Guard) => {
    if (confirm(`确认重置${guard.name}的密码？`)) {
      console.log('Resetting password for:', guard.name);
      alert(`${guard.name}的密码已重置为默认密码`);
    }
  };

  const handleDelete = (id: string) => {
    if (confirm('确认删除该门卫账号？此操作不可恢复。')) {
      setGuards(guards.filter(guard => guard.id !== id));
    }
  };

  const togglePermission = (permission: string) => {
    setFormData(prev => ({
      ...prev,
      permissions: prev.permissions.includes(permission)
        ? prev.permissions.filter(p => p !== permission)
        : [...prev.permissions, permission]
    }));
  };

  return (
    <div className="max-w-7xl mx-auto">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">门卫账号管理</h2>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                管理门卫账号信息、权限分配和状态控制
              </p>
            </div>
            <button
              onClick={() => setShowAddModal(true)}
              className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
            >
              <Plus className="h-4 w-4 mr-2" />
              添加门卫
            </button>
          </div>
        </div>

        <div className="p-6">
          {/* Search and filters */}
          <div className="flex flex-col lg:flex-row gap-4 mb-6">
            <div className="flex-1 relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center">
                <Search className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="搜索姓名或工号..."
              />
            </div>
            
            <div className="flex gap-2">
              <select
                value={filterDistrict}
                onChange={(e) => setFilterDistrict(e.target.value)}
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              >
                <option value="all">全部院区</option>
                {districts.map(district => (
                  <option key={district} value={district}>{district}</option>
                ))}
              </select>
              
              <select
                value={filterStatus}
                onChange={(e) => setFilterStatus(e.target.value)}
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              >
                <option value="all">全部状态</option>
                <option value="active">启用</option>
                <option value="inactive">禁用</option>
              </select>
            </div>
          </div>

          {/* Guard list */}
          {filteredGuards.length === 0 ? (
            <div className="text-center py-12">
              <Users className="mx-auto h-12 w-12 text-gray-400 mb-4" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                {searchTerm || filterDistrict !== 'all' || filterStatus !== 'all' 
                  ? '没有找到匹配的门卫账号' 
                  : '暂无门卫账号'
                }
              </h3>
              <p className="text-gray-600 dark:text-gray-400">
                {searchTerm || filterDistrict !== 'all' || filterStatus !== 'all'
                  ? '请尝试调整搜索条件或筛选器'
                  : '点击上方按钮添加第一个门卫账号'
                }
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {filteredGuards.map((guard) => (
                <div key={guard.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-start justify-between">
                    <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <div className="flex items-center mb-2">
                          <span className="font-medium text-gray-900 dark:text-white text-lg">
                            {guard.name}
                          </span>
                          <span className={`ml-3 px-2 py-1 text-xs rounded-full ${
                            guard.status === 'active'
                              ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                              : 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200'
                          }`}>
                            {guard.status === 'active' ? '启用' : '禁用'}
                          </span>
                        </div>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">
                          工号：{guard.employeeId}
                        </p>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">
                          管辖院区：{guard.district}
                        </p>
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                          创建时间：{guard.createdAt}
                        </p>
                        {guard.lastLogin && (
                          <p className="text-sm text-gray-600 dark:text-gray-400">
                            最后登录：{guard.lastLogin}
                          </p>
                        )}
                      </div>
                      
                      <div>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">权限设置：</p>
                        <div className="flex flex-wrap gap-1">
                          {guard.permissions.map((permission) => (
                            <span
                              key={permission}
                              className="px-2 py-1 text-xs bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 rounded"
                            >
                              {permission}
                            </span>
                          ))}
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center space-x-2 ml-4">
                      <button
                        onClick={() => handleEdit(guard)}
                        className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors"
                        title="编辑"
                      >
                        <Edit2 className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleToggleStatus(guard.id)}
                        className={`p-2 rounded transition-colors ${
                          guard.status === 'active'
                            ? 'text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20'
                            : 'text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20'
                        }`}
                        title={guard.status === 'active' ? '禁用账号' : '启用账号'}
                      >
                        {guard.status === 'active' ? <ShieldOff className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
                      </button>
                      <button
                        onClick={() => handleResetPassword(guard)}
                        className="p-2 text-yellow-600 hover:bg-yellow-50 dark:hover:bg-yellow-900/20 rounded transition-colors"
                        title="重置密码"
                      >
                        <RotateCcw className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(guard.id)}
                        className="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors"
                        title="删除账号"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Add/Edit Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-75 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-2xl mx-4 max-h-screen overflow-y-auto">
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
              {editingGuard ? '编辑门卫账号' : '添加门卫账号'}
            </h3>
            
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    姓名 *
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({...formData, name: e.target.value})}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    required
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    工号 *
                  </label>
                  <input
                    type="text"
                    value={formData.employeeId}
                    onChange={(e) => setFormData({...formData, employeeId: e.target.value})}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  管辖院区 *
                </label>
                <select
                  value={formData.district}
                  onChange={(e) => setFormData({...formData, district: e.target.value})}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  required
                >
                  {districts.map(district => (
                    <option key={district} value={district}>{district}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  权限设置 *
                </label>
                <div className="space-y-2">
                  {availablePermissions.map((permission) => (
                    <label key={permission} className="flex items-center">
                      <input
                        type="checkbox"
                        checked={formData.permissions.includes(permission)}
                        onChange={() => togglePermission(permission)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-900 dark:text-white">
                        {permission}
                      </span>
                    </label>
                  ))}
                </div>
              </div>

              <div className="flex space-x-3 pt-4">
                <button
                  type="button"
                  onClick={resetForm}
                  className="flex-1 px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-200 dark:bg-gray-600 rounded-md hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
                  disabled={formData.permissions.length === 0}
                >
                  {editingGuard ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};